<template>
  <div class="setting-center_mall-info-setting_commercial-tenant-edit">
    <el-form ref="commercialTenantForm" :model="params" :disabled="disabled" :rules="rules" label-width="7.5rem">
      <div class="base-info">
        <div class="icon-upload">
          <label><span>*</span> 商户Logo</label>
          <upload ref="upload" :disabled="diabledEdit" :limit="1" :file-list="logoFileList" :file-filter="['jpg', 'jpeg', 'png', 'icon', 'gif', 'bmp', 'JPG', 'JPEG', 'PNG', 'ICON', 'GIF', 'BMP']" />
          <label class="mt20"><span>*</span> 商户介绍</label>
          <el-input v-model="params.digest" type="textarea" :rows="15" :disabled="diabledEdit" />
        </div>
        <div class="basics-info">
          <el-row :gutter="40">
            <el-col :span="12">
              <el-form-item label="商户编号：" prop="code">
                <el-input v-model="params.code" :disabled="diabledEdit" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="对应铺位：" prop="storeIds">
                <el-cascader
                  v-model="params.storeIds"
                  :options="bunkList"
                  :props="bunkProps"
                  :disabled="diabledEdit"
                  clearable
                  @change="storeChange"
                  @focus="getBunkInfo"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商户名称：" prop="name">
                <el-input v-model="params.name" :disabled="diabledEdit" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="商户类型：" prop="type">
                <el-select v-model="params.type" :disabled="diabledEdit">
                  <el-option v-for="item in shopTypeList" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="经营模式：" prop="manage">
                <el-select v-model="params.manage" :disabled="diabledEdit">
                  <el-option v-for="item in businessModelList" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="负责人：" prop="responsibility">
                <el-input v-model="params.responsibility" :disabled="diabledEdit" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系手机：" prop="tel">
                <el-input v-model="params.tel" :disabled="diabledEdit" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="营业状态：" prop="bizStatus">
                <el-select v-model="params.bizStatus" :disabled="diabledEdit">
                  <el-option v-for="item in businessStatusList" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="营业面积：">
                <el-input v-model="params.bizArea" :disabled="diabledEdit" class="inputNumRight" />
                <!-- <el-input-number v-model="params.bizArea" :disabled="true" :precision="2" :controls="false" /> -->
                <label class="unit-info">平方</label>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="客服电话：" prop="customerServiceTelephone">
                <el-input v-model="params.customerServiceTelephone" :disabled="diabledEdit" />
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="联系邮箱：" prop="email">
                <el-input v-model="params.email" :disabled="diabledEdit" />
              </el-form-item>
            </el-col>
            <el-col :span="14">
              <el-form-item label="签约日期：" prop="contractTime">
                <el-date-picker v-model="params.contractTime" :disabled="diabledEdit" unlink-panels value-format="yyyy-MM-dd" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" @change="timeChange" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="品牌名称：" prop="brandIds">
                <div>
                  <span v-if="!disabled && !diabledEdit" class="blueBtn mr10" @click="openBrandDialog">选择</span>
                  <el-tag
                    v-for="tag in params.brands"
                    :key="tag.id"
                    :closable="!disabled && !diabledEdit"
                    :disable-transitions="false"
                    class="mr10"
                    @close="handleClose1(tag)"
                  >
                    {{ tag.name }}
                  </el-tag>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所属业态：">
                <el-cascader
                  v-model="params.formatId"
                  :disabled="true"
                  :options="options"
                  :props="props"
                />
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="商户公司：" prop="leaseeName">
                <el-input v-model="params.leaseeName" placeholder="请输入内容" :disabled="true">
                  <el-button slot="append" icon="el-icon-search" @click="leaseeDialogVisible = true" />
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24" class="flex-column">
              <el-form-item label="商户封面图：" prop="coverImgs">
                <div>
                  <upload ref="imgUpload" class="load-cont" :limit="diabledEdit?1:10" :disabled="diabledEdit" :file-list="uploadFileList" :file-filter="filterImgType" :name-show="false" @setKey="getUrl" />
                  <span>大小：1024*768</span>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </div>
    </el-form>
    <div class="btn-footer">
      <el-button @click="close">取消</el-button>
      <el-button v-if="!disabled && !diabledEdit" type="primary" @click="submit">保存</el-button>
    </div>
    <el-dialog v-if="innerDialog" title="选择" :close-on-click-modal="false" :visible.sync="innerDialog" append-to-body>
      <el-form class="search" label-position="right" label-width="6rem">
        <el-row :gutter="40">
          <el-col :span="8">
            <el-form-item label="品牌名称：">
              <el-input v-model="brandParams.name" />
            </el-form-item>
          </el-col>
          <el-col :span="8" class="mb15">
            <SearchButton :default-params="brandParams" @refreshParams="refreshParams" @getList="getList1" />
          </el-col>
        </el-row>
      </el-form>
      <vxe-table
        ref="listTree"
        border
        resizable
        highlight-hover-row
        :auto-resize="true"
        :data="brandList"
        width
        max-height="300"
        row-id="openId"
        highlight-current-row
        text-algin="center"
        :checkbox-config="{checkRowKeys: checkList, checkStrictly: false}"
        @checkbox-all="selectAll"
        @checkbox-change="selectChangeEvent"
      >
        <vxe-table-column type="checkbox" width="50" align="center" />
        <vxe-table-column field="name" title="品牌名称" />
      </vxe-table>
      <vxe-pager
        :current-page.sync="brandParams.pageNum"
        :page-size.sync="brandParams.pageSize"
        :total="brandTotal"
        :layouts="['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'FullJump', 'Total']"
        @page-change="getBrandList"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="innerDialog = false">取消</el-button>
        <el-button v-if="!disabled" type="primary" @click="clickSure">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog v-if="leaseeDialogVisible" width="60%" title="选择" :close-on-click-modal="false" :visible.sync="leaseeDialogVisible" append-to-body>
      <div class="card-list">
        <el-card shadow="never" class="selectCard searchColumn">
          <el-form ref="ruleForm" label-position="right" :model="params" :rules="rules" label-width="6rem">
            <el-row :gutter="40">
              <el-col :span="10">
                <el-form-item label="名称：" prop="leaseeName">
                  <el-input v-model="leaseeParams.leaseeName" style="width: 240px;" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="联系电话：" prop="leaseePhone">
                  <el-input v-model="leaseeParams.leaseePhone" style="width: 240px;" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <SearchButton :default-params="chooseParams" @refreshParams="refreshLeaseeParams" @getList="getLeaseeList1" />
              </el-col>
            </el-row>
          </el-form>
        </el-card>
        <el-card shadow="never" class="tableCard">
          <vxe-toolbar :refresh="{query: getLeaseeList}" />
          <vxe-table
            ref="listLeasee"
            border
            resizable
            highlight-hover-row
            :auto-resize="true"
            :data="leaseeList"
            width
            max-height="300"
            highlight-current-row
            :radio-config="{highlight: true}"
            text-algin="center"
          >
            <vxe-table-column type="radio" width="80" />
            <vxe-table-column min-width="220" field="leaseeName" title="公司/个人" />
            <vxe-table-column width="220" field="typeName" title="性质" />
            <vxe-table-column width="180" field="contacterName" title="联系人" />
            <vxe-table-column width="150" field="contacterPhone" title="联系电话" />
          </vxe-table>
          <vxe-pager
            :current-page.sync="leaseeParams.pageNum"
            :page-size.sync="leaseeParams.pageSize"
            :total="leaseeTotal"
            :layouts="['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'FullJump', 'Total']"
            @page-change="getLeaseeList"
          />
        </el-card>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="leaseeDialogVisible = false">取消</el-button>
        <el-button v-if="!disabled" type="primary" @click="clickLeaseeSure">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import SearchButton from '@/components/SearchButton'
import upload from '@/components/upload'
import valid from '@/utils/valid'
import { getBunkTreeList } from '@/api/bunk'
import { getBrandList, getBrand } from '@/api/brand'
import { addShops, modifyShops, getShops, getVersionstatTreeList, lesseePageList } from '@/api/tenement'
import { searchAllDictionaries } from '@/api/public'
import { filterPriceInput } from '@/utils/filter'
export default {
  components: {
    SearchButton,
    upload
  },
  props: {
    disabled: {
      type: Boolean,
      required: false,
      default: false
    },
    diabledEdit: {
      type: Boolean,
      required: false,
      default: true
    },
    parentId: {
      type: String,
      required: false,
      default: ''
    },
    floorId: {
      type: String,
      required: false,
      default: ''
    }
  },
  data() {
    return {
      arrList: [],
      leaseeDialogVisible: false,
      leaseeParams: {},
      leaseeTotal: 0,
      leaseeList: [],
      brandParams: {},
      brandTotal: 0,
      brandList: [],
      checkList: [],
      innerDialog: false,
      fileList: [],
      logoUrl: '',
      shopTypeList: [],
      businessModelList: [],
      filterImgType: ['jpg', 'jpeg', 'png', 'icon', 'gif', 'bmp', 'JPG', 'JPEG', 'PNG', 'ICON', 'GIF', 'BMP'],
      businessStatusList: [],
      logoFileList: [],
      uploadFileList: [],
      props: {
        children: 'children',
        value: 'id',
        label: 'name',
        emitPath: false
      },
      bunkProps: {
        children: 'child',
        label: 'name',
        value: 'id',
        emitPath: false,
        multiple: true
      },
      bunkList: [],
      params: {
        brands: [],
        storeIds: [],
        brandIds: []
      },
      options: [],
      rules: {
        code: [
          { required: true, message: '请输入商户编号', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入商户名称', trigger: 'blur' }
        ],
        brandIds: [
          { type: 'array', required: true, message: '请选择品牌', trigger: 'change' }
        ],
        responsibility: [
          { required: true, message: '请输入负责人', trigger: 'blur' }
        ],
        tel: [
          { required: true, message: '请填写手机号', trigger: 'blur' },
          { min: 11, max: 11, message: '长度为11个数字', trigger: 'blur' },
          { validator: valid.mobile, trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择商户类型', trigger: 'change' }
        ],
        manage: [
          { required: true, message: '请选择经营模式', trigger: 'change' }
        ],
        bizStatus: [
          { required: true, message: '请选择营业状态', trigger: 'change' }
        ],
        contractTime: [
          { type: 'array', required: true, message: '请选择合同签约时间', trigger: 'change' }
        ],
        coverImgs: [{ type: 'array', required: true, message: '请选择图片', trigger: 'change' }]
      },
      filterMethod(query, item) {
        return item.name.indexOf(query) > -1
      }
    }
  },
  created() {
    this.getDicInfo('shop_type')
    this.getDicInfo('business_model')
    this.getDicInfo('business_status')
    this.getTreeInfo(1)
    // this.getTreeInfo(2)
    // this.getBrandInfo()
    this.getBunkInfo()
  },
  methods: {
    // 合同签约时间
    timeChange(el) {
      this.$set(this.params, 'contractBeginTime', el[0])
      this.$set(this.params, 'contractEndTime', el[1])
    },
    getUrl(arr) {
      if (arr.length === 0) {
        this.$refs.commercialTenantForm.validateField('coverImgs')
      } else {
        this.$refs.commercialTenantForm.clearValidate('coverImgs')
      }
      this.params.coverImgs = arr.map(item => item.urlName)
    },
    handleClose1(tag) {
      this.params.brands = this.params.brands.filter(item => item.id !== tag.id)
      this.params.brandIds = this.params.brandIds.filter(item => item !== tag.id)
    },
    getLeaseeList() {
      lesseePageList(this.leaseeParams).then(res => {
        this.leaseeList = res.records
        this.total = res.total
      })
    },
    getLeaseeList1() {
      this.leaseeParams.pageNum = 1
      this.getLeaseeList()
    },
    refreshLeaseeParams(params) {
      this.leaseeParams = params
    },
    clickLeaseeSure() {
      if (this.$refs.listLeasee.getRadioRecord()) {
        const selectedRow = JSON.parse(JSON.stringify(this.$refs.listLeasee.getRadioRecord()))
        this.params.leaseeName = selectedRow.leaseeName
        this.params.leaseeId = selectedRow.id
        this.leaseeDialogVisible = false
      }
    },
    refreshParams(params) {
      this.brandParams = params
    },
    selectAll(e) {
      if (e.checked) {
        this.checkList.push(...e.records.map(item => item.id))
        this.checkList = Array.from(new Set(this.checkList))
        this.arrList.push(...e.records.map(item => {
          return {
            id: item.id,
            name: item.name,
            introduce: item.introduce
          }
        }))
        const arr2 = []
        this.checkList.forEach(item => {
          arr2.push(this.arrList.filter(it => it.id === item)[0])
        })
        this.arrList = arr2
      } else {
        const arr = this.brandList.map(item => item.id)
        const arr1 = []
        this.checkList.forEach((item, index) => {
          arr.forEach(it => {
            if (item === it) {
              arr1.push(index)
            }
          })
        })
        arr1.reverse().forEach(item => {
          this.checkList.splice(item, 1)
          this.arrList.splice(item, 1)
        })
      }
    },
    selectChangeEvent(row) {
      let i = -1
      if (this.checkList === null) {
        this.checkList = []
      } else {
        this.checkList.forEach((item, index) => {
          if (item === row.row.id) {
            i = index
          }
        })
      }
      if (i === -1) {
        this.checkList.push(row.row.id)
        this.arrList.push({ id: row.row.id, name: row.row.name, introduce: row.row.introduce })
        const arr2 = []
        this.checkList.forEach(item => {
          if (this.arrList.filter(it => it.id === item).length > 0) arr2.push(this.arrList.filter(it => it.id === item)[0])
        })
        this.arrList = arr2
      } else {
        this.checkList.splice(i, 1)
        this.arrList.splice(i, 1)
      }
    },
    getList1() {
      this.brandParams.pageNum = 1
      this.getBrandList()
    },
    getBrandList() {
      getBrandList(this.brandParams).then(res => {
        this.$nextTick(() => {
          if (this.checkList !== null) {
            this.checkList.forEach((item, index) => {
              res.records.forEach((it, idx) => {
                if (item === it.id) {
                  this.$refs.listTree.setCheckboxRow(res.records[idx], true)
                }
              })
            })
          }
          this.brandList = res.records
          this.brandTotal = res.total
        })
      })
    },
    clickSure() {
      if (this.checkList.length === 0) {
        this.$message.error('请选择品牌')
        return false
      }
      getBrand(this.checkList[0]).then(res => {
        this.logoFileList = [{ url: res.logo }]
        this.params.digest = this.arrList[0].introduce
        this.params.formatId = res.formatId
        this.params.brandIds = JSON.parse(JSON.stringify(this.checkList))
        this.params.brands = JSON.parse(JSON.stringify(this.arrList))
        this.innerDialog = false
      })
    },
    openBrandDialog() {
      this.brandParams = {
        pageNum: 1,
        pageSize: 20
      }
      this.getBrandList()
      this.checkList = JSON.parse(JSON.stringify(this.params.brandIds))
      this.arrList = JSON.parse(JSON.stringify(this.params.brands))
      this.innerDialog = true
    },
    storeChange(event) {
      this.params.bizArea = 0
      const _this = this
      event.forEach(e => {
        this.bunkList.forEach(item => {
          if (item.child && item.child.length > 0) {
            item.child.forEach(item2 => {
              if (item2.child && item2.child.length > 0) {
                const area = item2.child.find(info => info.id === e)
                if (area) {
                  _this.params.bizArea += parseFloat(area.buildArea)
                }
              }
            })
          }
        })
      })
    },
    brandChagne(event) {
      const _this = this
      const formatItem = this.brandList.find(item => item.id === _this.params.brandIds[0])
      this.params.formatId = formatItem ? formatItem.formatId : ''
    },
    getBunkInfo() {
      getBunkTreeList({
        id: this.parentId,
        contractBeginTime: this.params.contractBeginTime,
        contractEndTime: this.params.contractEndTime
      }).then(response => {
        this.bunkList = response
        if (this.parentId) {
          this.getInfo(this.parentId)
        }
      })
    },
    close() {
      this.$emit('close')
    },
    // getBrandInfo() {
    //   getBrandList().then(response => {
    //     this.brandList = response
    //   })
    // },
    getDicInfo(type) {
      searchAllDictionaries({
        type: type
      }).then(response => {
        if (type === 'business_model') {
          this.businessModelList = response
        } else if (type === 'shop_type') {
          this.shopTypeList = response
        } else if (type === 'business_status') {
          this.businessStatusList = response
        }
      })
    },
    getTreeInfo(type) {
      getVersionstatTreeList({
        type: type,
        parentId: '0'
      }).then(response => {
        if (type === 1) {
          this.options = response
        }
      })
    },
    submit() {
      if (this.$demoUser.checkUser()) {
        alert('演示账号，不能执行此操作')
        return
      }
      if (this.$refs.upload.key.length === 0) {
        this.$message.error('请上传品牌LOGO')
        return
      }
      if (!this.params.digest) {
        this.$message.error('请填写商户介绍')
        return
      }
      this.params.floor = this.floorId || this.params.floor
      this.params.logo = this.$refs.upload.key[0].urlName
      this.$refs.commercialTenantForm.validate(valid => {
        if (valid) {
          if (!this.parentId) {
            addShops(this.params).then(response => {
              this.$message.success('添加成功')
              this.$emit('refresh')
            })
          } else {
            modifyShops(this.params).then(response => {
              this.$message.success('修改成功')
              this.$emit('refresh')
            })
          }
        }
      })
    },
    getInfo(id) {
      getShops(id).then(response => {
        this.params = response
        this.logoFileList = [
          {
            url: this.params.logo
          }
        ]
        this.uploadFileList = []
        this.params.coverImgs.forEach(item => {
          this.uploadFileList.push({
            url: item
          })
        })
        this.params.type = this.params.type.toString()
        this.params.manage = this.params.manage.toString()
        this.params.bizStatus = this.params.bizStatus.toString()
        this.storeChange(this.params.storeIds)
        this.$set(this.params, 'bizArea', filterPriceInput(this.params.bizArea))
        this.$set(this.params, 'contractTime', [this.params.contractBeginTime === null ? '' : this.params.contractBeginTime, this.params.contractEndTime === null ? '' : this.params.contractEndTime])
      })
    }
  }
}
</script>

<style lang="scss">
  .setting-center_mall-info-setting_commercial-tenant-edit {
    .btnList {
      display: flex;
      justify-content:center;
    }
    .upload-img-label {
      margin-bottom: 15px;
      display: inline-block;
    }
    .base-info {
      display: flex;
      margin-bottom: 20px;
      .icon-upload {
        display: flex;
        flex-direction: column;
        align-items: center;
        margin-right: 40px;
        >label {
          margin-bottom: 10px;
          span {
            color: #ff4949;
          }
        }
        .el-upload {
          border: 1px dashed #d9d9d9;
          border-radius: 5px;
          margin: 0 30px;
          cursor: pointer;
          position: relative;
          overflow: hidden;
          .avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 150px;
            height: 150px;
            line-height: 150px;
            text-align: center;
          }
        }
      }
      .basics-info {
        width: 100%;
      }
    }
    .el-form-item  {
      margin-bottom: 30px;
      .unit-info {
        margin-left: 10px;
        min-width: 40px;
      }
    }
    .right-label-item {
      display: flex;
      align-items: center;
      .el-form-item__content {
        display: flex;
        align-items: center;
        >label {
          white-space: nowrap;
          margin-left: 5px;
        }
      }
    }
    .flex-column {
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      .el-form-item {
        margin-bottom: 10px !important;
      }
    }
    .logoImg {
      width: 148px;
      height: 148px;
      border: 1px dashed #d9d9d9;
      >img {
        width: 100%;
        height: 100%;
      }
    }
    textarea {
      max-height: 395px;
    }
  }
  .load-cont{
    .el-upload--picture-card{
      width: 300px;
      height: 200px;
      line-height:200px;
     }
    .el-upload-list__item{
      width: 300px;
      height: 200px;
    }
  }
</style>
